import socket
import coder
import matplotlib.pyplot as plt
import time

# config
address = "192.168.10.160"
port = 5000
configs=[('input','',10),('ctrlAngle','',10),('angle','',10),('rpm','',100),('ctrl','',100)]
windowsSize=100

topicSize = configs.__len__()

times=[]
datas=[]
for i in range(topicSize):
    datas.append([])

plt.grid(True)
plt.ion()
lastStr=""

def OpResponse(response:str):
    if(response==''):
        return
    #print(response)
    plt.cla()
    state=coder.DecoderResponse(response)
    times.append(time.time())
    full = len(times)>windowsSize
    if(full):
        del times[0]
    for i in range(topicSize):
        datas[i].append(state[configs[i][0]]/configs[i][2])
        if(full):
            del datas[i][0]
    for i in range(topicSize):
        if configs[i][1]=='':
            plt.plot(times,datas[i],configs[i][1],label=configs[i][0])
        else:
            plt.plot(times,datas[i],label=configs[i][0])
    plt.legend(loc='upper right')
    plt.pause(0.01)

topics=[]
for i in range(topicSize):
    topics.append(configs[i][0])
s=socket.socket()

while(True):
    try:
        print("try connect to server...")
        s.connect((address,port))
        break
    except:
        time.sleep(1)
print("connecting to "+address+':'+str(port))
s.send(coder.EncodeRequest(topics).encode())

while(True):
    byteReturn = s.recv(1024)
    if not byteReturn:
        lastStr=""
        print("Disconnect to server.")
        break
    lastStr+= byteReturn.decode()
    while(True):
        repend = lastStr.find('\n')
        if repend < 0:
            break
        OpResponse(lastStr[0:repend+1])
        lastStr = lastStr[repend+1:]
s.close()
